package com.blockmeta.bbs.businesslibrary.widget.chartview.Layer;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;


import com.blockmeta.bbs.baselibrary.utils.DimentionsUtil;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.businesslibrary.util.Format2Util;
import com.blockmeta.bbs.businesslibrary.websocket.Symbol;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.Coordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.Axis.MoveCoordinate;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CandleData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.ChartData;
import com.blockmeta.bbs.businesslibrary.widget.chartview.CoinChart;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.Core;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.MInteger;
import com.blockmeta.bbs.businesslibrary.widget.tictactec.ta.lib.RetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

class BarMoveLayer extends BasicLayer
{
	List<CandleData> tMAList;
	private int mPeriod1 = 5;
	private int mPeriod2 = 10;
	private int beginIdx1, beginIdx2;
	private int m_color1 = 0xFF3898FF, m_color2 = 0xFFFF72A5;
	private String m_ma1 = "", m_ma2 = "";
	private String m_lastMa1 = "", m_lastMa2 = "";
	float txtSize;
	private float mTxtXLocation;
	public BarMoveLayer()
	{
		super();
	}

	@Override
	public boolean onCalculateData()
	{
		boolean m_ma_on = true;
		if (!m_ma_on)
		{
			tMAList = null;
			m_callback.setAdditionData(tMAList);//用于合并均线数据和k线数据的上下限
			return true;
		}

		ArrayList<String> params = new ArrayList<>(Arrays.asList("5", "10"));//FDTStorage.getInstance().getArray(SaveKey.CHART_INDICATOR_MA + "param", SaveKey.CHART_INDICATOR_PARAM);
		if (params != null)
		{
			mPeriod1 = FormatUtil.parseInt(params.get(0));
			mPeriod2 = FormatUtil.parseInt(params.get(1));
		}

		beginIdx1 = Integer.MAX_VALUE;
		beginIdx2 = Integer.MAX_VALUE;

		List<CandleData> tDataList = m_callback.getCandleDataList();
		int tListSize = tDataList.size();
		tMAList = new ArrayList<CandleData>();
		double[] volumn = new double[tListSize];

		for (int ii = 0; ii < tListSize; ii++)
		{
			volumn[ii] = tDataList.get(ii).m_lVolume;
		}
		//准备计算数组
		Core taLib = CoinChart.getTaLib();
		double[] ma1 = new double[tListSize];
		double[] ma2 = new double[tListSize];
		if (mPeriod1 != 0 && mPeriod1 <= tListSize)
		{
			beginIdx1 = doMaCalculate(volumn, taLib, mPeriod1, ma1);
		}
		if (mPeriod2 != 0 && mPeriod2 <= tListSize)
		{
			beginIdx2 = doMaCalculate(volumn, taLib, mPeriod2, ma2);
		}

		//得到结果数组,结果为有值的部分开始如0.006747350439404443 0.010591595301185919 0.0027601354459569905 -0.03422737187350222 -0.09373321549064784 -0.12136830634374718 -0.12757081986248053 -0.1250403123559245 -0.11954476938285197 -0.04594994628476812 0.009701854832457002 0.06010755762170561 0.09747712313834 0.13895129756983238 0.171272192598785 0.18158545677729165 0.15978420503275714 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
		//outBegIdx为是第几个开始的，outNbElement为有效的数字个数 ，如73个元素，那么outBegIdx为33，outNbElement为40 26-1+9-1=33
		CandleData candle = null;
		if (tListSize > 0)
		{
			double tMax = Double.MIN_VALUE, tMin = Double.MAX_VALUE;
			int i1 = 0, i2 = 0, i3 = 0, i4 = 0, i5 = 0, i6 = 0, i7 = 0;
			for (int i = 0; i < tListSize; i++)//修改数据源
			{
				candle = new CandleData();

				double max = Double.MIN_VALUE;
				double min = Double.MAX_VALUE;
				if (i >= beginIdx1 && mPeriod1 != 0)
				{
					double td = ma1[i1];
					candle.setDbOpen(td);
					if (td > max)
					{
						max = td;
					}
					if (td < min)
					{
						min = td;
					}
					i1++;
				}
				else
				{
					candle.setDbOpen(0.0);
				}
				if (i >= beginIdx2 && mPeriod2 != 0)
				{
					double td = ma2[i2];
					candle.setDbClose(td);
					if (td > max)
					{
						max = td;
					}
					if (td < min)
					{
						min = td;
					}
					i2++;
				}
				else
				{
					candle.setDbClose(0.0);
				}

				//再把最大和最小算出来放到两个字段里面
				candle.setHighForward(max);
				candle.setLowForward(min);

				tMAList.add(candle);
			}


			m_callback.setAdditionData(tMAList);//用于合并均线数据和k线数据的上下限
		}
		return true;
	}

	public int doMaCalculate(double[] volumns, Core taLib, int period, double[] ma)
	{
		MInteger outBegIdx = new MInteger();
		MInteger outNbElement = new MInteger();
		if(period != 1)
		{
			RetCode retCode = taLib.sma(0, volumns.length - 1, volumns, period, outBegIdx, outNbElement, ma);
		}
		else
		{
			outBegIdx.value = 0;
			for (int i = 0; i < ma.length; i++)
			{
				ma[i] = volumns[i];
			}
		}
		return outBegIdx.value;
	}

	@Override
	public Layer.ChartTypeEnum getLayerTypeEnum()
	{
		return Layer.ChartTypeEnum.MoveBar;
	}

	@Override
	public Coordinate createCoordinate()
	{
		return new MoveCoordinate();
	}

	@Override
	public void onDrawLayer(Canvas pCanvas, Paint pPaint, Point pPoint)
	{
		Coordinate tCoordinate = m_callback.getCoordinate();
		List<CandleData> tDataList = m_callback.getCandleDataList();
		List<CandleData> maList = tMAList;

		RectF tRectF = tCoordinate.getLayerRectF();

		// Bar 线的上分界线
//		pPaint.setColor(0xFFD3D8DE);
//		pPaint.setStrokeWidth(DimentionsUtil.dp2px(1));
//		pCanvas.drawLine(layer.left, layer.top, layer.right, layer.top, pPaint);
		Symbol symbol = m_callback.getCoordinate().tSymBol;
		int volumnDigit = 2;
		int priceDigit = 2;
		if(symbol != null) {
			volumnDigit = symbol.getVolumnDigit();
			priceDigit = symbol.getDigit();
		}

		float tCloseFloat = 0;
		float tOpenFloat = 0;
		float tHighFloat = 0;
		float tLowFloat = 0;
		float tValueFloat = 0;
		float tVolumnLong = 0;
		float tBeforeCloseFloat = 0;
		float tAvgFloat = 0;

		CandleData tTimeCandle = null;

		int tXPoint = pPoint.x;

		if (tDataList != null && tDataList.size() > 0)
		{
			int tListSize = tDataList.size();
			int tStartIndex = tCoordinate.getStartIndex();
			float tXFirstPosition = tCoordinate.getXFirstPosition();
			float tXInterval = tCoordinate.getXInterval();
			float tYFirstposition = tCoordinate.getYFirstPosition();
			float scaleFactor = tCoordinate.getScaleFactor();
			float tYMaxValue = tCoordinate.getMaxValue();

			float tYMinValue = 0;//tCoordinate.getMinValue();
			float tYValueDist = tYMaxValue - tYMinValue;
//			FDTLogUtils.d("tingchart","tYValueDist"+tYValueDist);
			float tYValueLength = tCoordinate.getValueHeight();

			float tCurrentYPosition = 0.f;
			float tTempYPosition = 0.f;
			float tCurrentXPosition = 0.f;
			float tTempXPosition = 0.f;
			float tCurrentYPosition1 = 0.f;
			float tTempYPosition1 = 0.f;

			float tCurrentYPosition2 = 0.f;
			float tTempYPosition2 = 0.f;
			boolean tStartDraw1 = false, tStartDraw2 = false;

			pPaint.setAntiAlias(true);
			pPaint.setColor(m_callback.getColor());
			pPaint.setStrokeWidth(2f);



			float tBarWidth = Math.min(tXInterval / 3, 25);

			int tSysUpColor = m_callback.getSysUpColor();
			int tSysDownColor = m_callback.getSysDownColor();
			int tSysEvenColor = m_callback.getSysEvenColor();

			int displayCount = m_callback.getDisplayCount();//获取当前要显示的个数
			int minCount = Math.min(tStartIndex+displayCount,tListSize);//不能超出数据集宽度

			if(m_callback.isDrawAllData())//如果需要绘制全部数据的
			{
				tStartIndex = 0;
				minCount = tListSize;
			}
//			FDTLogUtils.d("tingchart","barmovelayer from draw tStartIndex"+tStartIndex+" to mincount"+minCount);
			for (int i = tStartIndex; i < minCount; i++)
			{
				CandleData tCandleData;

				try
				{
					tCandleData = tDataList.get(i);
				}
				catch (Exception e)
				{
					continue;
				}
				CandleData candle = maList.get(i);


				if (tCandleData == null || candle == null)
					continue;
				float tMa1 = (float) candle.getDbOpen();
				float tMa2 = (float) candle.getDbClose();
				float tHigh = (float) tCandleData.getDbHigh();//获取当前点的数据
				float tLow = (float) tCandleData.getDbLow();
				float tOpen = (float) tCandleData.getDbOpen();
				float tClose = (float) tCandleData.getDbClose();
				float tAvg = (float) tCandleData.m_dbAvgPx;
				float tVolumn = tCandleData.m_lVolume;
				tTempXPosition = tCurrentXPosition;
				tCurrentXPosition = tXFirstPosition + tXInterval * (i - tStartIndex);
				tTempYPosition = tCurrentYPosition;
				tCurrentYPosition = tYFirstposition - ((tVolumn - tYMinValue) * tYValueLength / tYValueDist);

				if (((tCurrentXPosition - tXInterval / 2) <= pPoint.x && pPoint.x < (tCurrentXPosition + tXInterval / 2)) || ((i == minCount - 1) && pPoint.x > tCurrentXPosition + tXInterval / 2) || (i == tStartIndex && pPoint.x < tCurrentXPosition - tXInterval / 2))
				{
					float tValueaa = (tYFirstposition - pPoint.y) * tYValueDist / tYValueLength + tYMinValue;
					tValueFloat = tValueaa;
					tVolumnLong = tVolumn;
					tCloseFloat = tClose;
					tOpenFloat = tOpen;
					tHighFloat = tHigh;
					tLowFloat = tLow;
					m_ma1 = FormatUtil.getFormatString(tMa1, volumnDigit);
					m_ma2 = FormatUtil.getFormatString(tMa2, volumnDigit);

					tTimeCandle = tDataList.get(i);
					tAvgFloat = tAvg;

					tXPoint = (int) tCurrentXPosition;

					try
					{
						if (i > 0)
						{
							float tBeforeClose = (float) tDataList.get(i - 1).getDbClose();
							tBeforeCloseFloat = tBeforeClose;
						}else
						{
							tBeforeCloseFloat = 0;
						}
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				if (tOpen > tClose || (tOpen == tClose && i != 0 && tClose < (float) tDataList.get(i - 1).getDbClose()))
				{
					pPaint.setColor(tSysDownColor);
				}
//				else if (tOpen == tClose)
//				{
//					pPaint.setColor(tSysEvenColor);
//				}
				else
				{
					pPaint.setColor(tSysUpColor);
				}
//				FDTLogUtils.d("tingchart","draw chart i"+i+" tRectTopPosition"+tCurrentYPosition+" "+tYFirstposition);
				pCanvas.drawRect(tCurrentXPosition - tBarWidth, tCurrentYPosition, tCurrentXPosition + tBarWidth, tYFirstposition, pPaint);


				if (tMa1 != 0.0)
				{

					tTempYPosition1 = tCurrentYPosition1;
					tCurrentYPosition1 = tYFirstposition - ((tMa1 - tYMinValue) * tYValueLength / tYValueDist);

					if (tStartDraw1)
					{

							if (i > beginIdx1)//如果ma5，beginidx就是4，所以要到第6个点画线
							{
								pPaint.setColor(m_color1);
								drawLine(pCanvas, pPaint, tCurrentYPosition1, tTempYPosition1, tCurrentXPosition, tTempXPosition, tRectF);
							}

					}
					else
					{
						tStartDraw1 = true;
					}
				}

				if (tMa2 != 0.0)
				{
					tTempYPosition2 = tCurrentYPosition2;
					tCurrentYPosition2 = tYFirstposition - ((tMa2 - tYMinValue) * tYValueLength / tYValueDist);

					if (tStartDraw2)
					{

							if (i > beginIdx2)//如果ma5，beginidx就是4，所以要到第6个点画线
							{
								pPaint.setColor(m_color2);
								drawLine(pCanvas, pPaint, tCurrentYPosition2, tTempYPosition2, tCurrentXPosition, tTempXPosition, tRectF);
							}

					}
					else
					{
						tStartDraw2 = true;
					}
				}
			}

			CandleData candle = maList.get(minCount - 1);
			if (candle != null)
			{
				m_lastMa1 = FormatUtil.getFormatString(candle.getDbOpen(), volumnDigit);
				m_lastMa2 = FormatUtil.getFormatString(candle.getDbClose(), volumnDigit);
			}
		}

		ChartData.ChartPeroid tChartType = m_callback.getChartType();

		String time = tTimeCandle == null ? "" : getDisplayX(tChartType, tTimeCandle);
		String value = FormatUtil.longToVolumeHumanReadableFormat((long) tValueFloat, 2);

		setCrossData(pCanvas, pPaint, time, value, new Point(tXPoint, pPoint.y));

		RectF tLayerRect = tCoordinate.getLayerRectF();

		if (tLayerRect.contains(tXPoint, pPoint.y))
		{
			HashMap<String, String> tMap = new HashMap<String, String>();
			tMap.put("Close", tCloseFloat == 0 ? "" : FormatUtil.getFormatString(tCloseFloat, priceDigit));
			tMap.put("Open", tOpenFloat == 0 ? "" : FormatUtil.getFormatString(tOpenFloat, priceDigit));
			tMap.put("High", tHighFloat == 0 ? "" : FormatUtil.getFormatString(tHighFloat, priceDigit));
			tMap.put("Low", tLowFloat == 0 ? "" : FormatUtil.getFormatString(tLowFloat, priceDigit));
			tMap.put("BeforeClose", tBeforeCloseFloat == 0 ? "" : FormatUtil.getFormatString(tBeforeCloseFloat, priceDigit));
			tMap.put("Volumn", tVolumnLong == 0 ? "" : Format2Util.doubleToHumanReadableFormat(tVolumnLong, volumnDigit));
			tMap.put("Time", time);
			tMap.put("Avg", tAvgFloat == 0 ? "" : FormatUtil.getFormatString(tAvgFloat, priceDigit));
			m_callback.pointFeedback(tMap,pPoint );
		}
	}

	private void drawLine(Canvas pCanvas, Paint pPaint, float tCurrentYPosition, float tTempYPosition, float tCurrentXPosition, float tTempXPosition, RectF tRectF)
	{
		pCanvas.drawLine(tTempXPosition, tTempYPosition, tCurrentXPosition, tCurrentYPosition, pPaint);
	}

	@Override
	public void drawYesterClose(Canvas pCanvas, Paint pPaint)
	{
	}

	@Override
	public void drawFloatIndicatorText(boolean longtouch, Canvas pCanvas, Paint pPaint)
	{

		if (!m_callback.needFloatIndicatorText())
		{
			return;
		}

		txtSize = DimentionsUtil.dp2px(10);

		boolean m_ma_on = true;

		if (!m_ma_on)
		{
			return;
		}

		List<CandleData> tDataList = m_callback.getCandleDataList();
		if (tDataList == null || tDataList.size() == 0)
		{
			resetIndicatorData();
		}

		Coordinate tCoordinate = m_callback.getCoordinate();
		RectF tLayerRect = tCoordinate.getLayerRectF();
		RectF tChartRect = tCoordinate.getChartRectF();

		float tLeftPadding = DimentionsUtil.dp2px(0);
		float tButtomPadding = DimentionsUtil.dp2px(2);
		float tWordPadding = txtSize;

		//根据需要添加相应的均线数据上去
		pPaint.reset();
		pPaint.setTextSize(txtSize);
		pPaint.setAntiAlias(true);
		float textHeight = txtSize;
		mTxtXLocation = tLayerRect.left + tLeftPadding;
		float space = 0.f;


		space =  DimentionsUtil.dp2px(1) + 1;


		drawIndicator(mPeriod1, m_ma1, m_lastMa1, m_color1, longtouch, pCanvas, pPaint, tLayerRect, tChartRect, tLeftPadding, tButtomPadding, tWordPadding, textHeight, space);
		drawIndicator(mPeriod2, m_ma2, m_lastMa2, m_color2, longtouch, pCanvas, pPaint, tLayerRect, tChartRect, tLeftPadding, tButtomPadding, tWordPadding, textHeight, space);


	}

	public void drawIndicator(int period, String cValue, String lastValue, int color, boolean longtouch, Canvas pCanvas, Paint pPaint, RectF tLayerRect, RectF tChartRect, float tLeftPadding, float tButtomPadding, float tWordPadding, float textHeight, float tSpace)
	{
		if (period != 0)
		{
			String indicatorText;
			if (longtouch)
			{
				indicatorText = "MA" + period + " " + cValue;
			}
			else
			{
				indicatorText = "MA" + period + " " + lastValue;
			}
			float textWidth = pPaint.measureText(indicatorText);
			pPaint.setColor(color);
//

			float textY = tLayerRect.top + tSpace + txtSize;
			pCanvas.drawText(indicatorText, mTxtXLocation, textY, pPaint);
			mTxtXLocation += textWidth + tWordPadding;
		}
	}

	private void resetIndicatorData()
	{
		m_ma1 = "";
		m_ma2 = "";
		m_lastMa1 = "";
		m_lastMa2 = "";
	}

}
